// ==UserScript==
// @name         群障碍监控10.0
// @namespace    https://bbs.tampermonkey.net.cn/
// @version      10.0
// @description  try to take over the world!
// @author       MrLiu,DXM
// @match        http://10.245.0.60:6038/wms/
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // https://oapi.dingtalk.com/robot/send?access_token=69cf623f95de16a8ea5b700e0547b70f17e5d220bc0cd57a765f1964342cb0a6
    const oApi = 'https://oapi.dingtalk.com/robot/send?access_token=';
    const accessToken = '69cf623f95de16a8ea5b700e0547b70f17e5d220bc0cd57a765f1964342cb0a6';

    const testMobileInfo = {
        '永清县': '15630633523',
        '廊坊市区': '16633697998',
        '开发区': '18603167985',
        '霸州市': '16633697996',
        '固安县': '18603164972',
        '燕郊': '16633697909',
        'admin': '18603168805',
    };

    const regionManagerToMobile = {
        '固安县': '18603167524',
        '胜芳': '18603162465',
        '大城县': '18631628482',
        '文安县': '18631603172',
        '燕郊': '18603167045',
        '香河县': '18603167179',
        '三河市': '15531611098',
        '大厂回族自治县': '18603167239',
        '永清县': '18603167370',
        '广阳区': '18603169685',
        '安次区': '18633600080',
        '经济技术开发区': '18603167985',
        '霸州市': '18603164997',
        'admin': '18603168805',
        'MrLiu': '16633697996',
        'MrHe': '16633697909',
    };

    var queryResultRows;
    var runFlag = false;
    const allQueryInfo = new Map();

    getObjectsAndSetCilckFunction();

    //
    function sendDingTalkMessage(token, messages, atMobiles = []) {

        let url = oApi + token;

        console.log(url);

        var payload = JSON.stringify({
            msgtype: 'text',
            text: {
                content: messages,
            },
            at: {
                isAtAll: false,
                atMobiles: atMobiles,
            },
        });

        GM_xmlhttpRequest({
            method: 'POST',
            url: url,
            data: payload,
            headers: {
                'Content-Type': 'application/json',
            },
            onload: function(response) {
                if (response.status === 200) {
                    var responseData = JSON.parse(response.responseText);
                    if (responseData.errcode === 0) {
                        console.log('消息发送成功');
                    } else {
                        console.error('消息发送失败', responseData);
                    }
                } else {
                    console.error('发送消息时发生错误', response.status);
                }
            },
            onerror: function(response) {
                console.error('发送消息时发生错误', response.statusText);
            },
        });
    }

    //
    function getObjectsAndSetCilckFunction() {
        const sendMsg = document.querySelector("div.h_top");
        const newObjBtn = document.createElement("button");
        sendMsg.appendChild(newObjBtn);
        newObjBtn.innerHTML = "启动监控程序";
        newObjBtn.onclick = function() {
            startMonitoring();
        }
        
    };

    //
    async function startMonitoring() {
        async function repeatTask() {
            if(runFlag) {
                return;
            } else {
                runFlag = true;
                try {
                    await runFirstToSeven();
                    console.log(allQueryInfo);
                } catch (error) {
                    console.error('执行过程中出现错误:', error);
                } finally {
                    runFlag = false;
                }
            }
        }
        await repeatTask();
        setInterval(async () => {
            await repeatTask();
        }, 5 * 60 * 1000);
    }


    //  获取信息
    async function extractDataAndSendMessage() {
    }

    // 
    function parseTimeString(timeString) {
        const regex = /(\d+)天(\d+)时(\d+)分(\d+)秒/;
        const match = timeString.match(regex);
        if (!match) {
            throw new Error('输入的时间格式不正确，应为 X 天 X 时 X 分 X 秒');
        }
        const days = parseInt(match[1], 10);
        const hours = parseInt(match[2], 10);
        const minutes = parseInt(match[3], 10);
        const seconds = parseInt(match[4], 10);
        return days * 24 + hours + minutes / 60 + seconds / 3600;
    }

    // first Step
    // click 4947_tab
    function findAndClickGroupObstacleManagement() {
        return new Promise((resolve, reject) => {
            let btnGroupObstacleManagement = document.getElementById("4947_tab");
            if (!btnGroupObstacleManagement) {
                reject(new Error("执行第一步，未找到群障管理按钮。"));
            }
            if (btnGroupObstacleManagement.textContent === "群障管理") {
                btnGroupObstacleManagement.click();
                resolve();
            } else {
                reject(new Error("执行第一步，定位群障管理按钮时，按钮文本内容不匹配。"));
            }
        });
    }

    // Second Step
    function findAndClickGroupObstacleQuery() {
        return new Promise((resolve, reject) => {
            let linksGroupObstacleQuery = document.querySelectorAll("a.twohref");
            if(linksGroupObstacleQuery.length === 0) {
                reject(new Error("执行第二步，未找到群障查询链接。"));
                return;
            }
            for(let link of linksGroupObstacleQuery) {
                if (link.textContent === "群障查询") {
                    link.click();
                    resolve();
                    return;
                }
            }
            reject(new Error("执行第二步，找到群障查询相关链接，但未找到文本为 '群障查询' 的链接。"));
        });
    }

    // Three Step
    function locateAndSetGroupObstacleType() {
        return new Promise((resolve, reject) => {
            let iframeElements = document.getElementsByName("mainFrame");
            if(iframeElements.length === 0) {
                reject(new Error('未找到 class 为 mainFrame 的 iframe 元素'));
                return;
            }
            let iframeMainDocument = iframeElements[0].contentDocument || iframeElements[0].contentWindow.document;
            let setValueObject = iframeMainDocument.getElementById("gfClass");
            setValueObject.value = "4";
            resolve();
        });
    }

    // Four Step
    function locateAndSetGroupObstacleState(){
        return new Promise((resolve,reject) => {
            let iframeElements = document.getElementsByName("mainFrame");
            if(iframeElements.length === 0) {
                reject(new Error('未找到 class 为 mainFrame 的 iframe 元素'));
                return;
            }
            let iframeMainDocument = iframeElements[0].contentDocument || iframeElements[0].contentWindow.document;
            let setValueObject = iframeMainDocument.getElementById("repairedFlag");
            setValueObject.value = "0";
            resolve();
        });
    }

    // Five Step
    function locateAndClickTheQueryButton() {
        return new Promise((resolve,reject) => {
            let iframeElements = document.getElementsByName("mainFrame");
            if(iframeElements.length === 0) {
                reject(new Error('未找到 class 为 mainFrame 的 iframe 元素'));
                return;
            }
            let iframeMainDocument = iframeElements[0].contentDocument || iframeElements[0].contentWindow.document;
            let searchButtons = iframeMainDocument.querySelectorAll("a.btn.btn_sp");
            if (searchButtons.length === 0) {
                reject(new Error('在 iframe 中未找到 a.btn.btn_sp 的元素'));
                return;
            }
            for (let searchButton of searchButtons) {
                if (searchButton.innerText === "查询") {
                    searchButton.click();
                    resolve();
                    return;
                }
            }
        });
    }

    // Six Step
    async function getInputData() {
        return new Promise(async (resolve,reject) => {
            let sendMsgFlag;
            
            let iframeElements = document.getElementsByName("mainFrame");
            let iframeMainDocument = iframeElements[0].contentDocument || iframeElements[0].contentWindow.document;
            queryResultRows = iframeMainDocument.getElementById('resultTbl1').querySelectorAll('tr');
            for(let i = 0; i < queryResultRows.length; i++) {
                let atMobiles = []; 
                sendMsgFlag = false;
                let row = queryResultRows[i];
                let thisRadio = row.querySelector('input[type="checkbox"]');
                let gforderid = row.getAttribute('gforderid');
                let cells = queryResultRows[i].querySelectorAll('td');
                let gfName = cells[3].innerText.trim();
                let region = cells[5].innerText.trim();
                let nodeInfo = cells[11].innerText.trim();
                let duration = cells[15].innerText.trim();
                let affectedUsers = cells[21].innerText.trim();
                let installer = cells[22].innerText.trim();
                let smsCount = cells[23].innerText.trim();
                let nodeInfoName = nodeInfo.split(',');
                let sendMessageTitle;
                if (affectedUsers >= 0) {
                    if(region === "廊坊市区") {
                        atMobiles.push(regionManagerToMobile['安次区']);
                        atMobiles.push(regionManagerToMobile['广阳区']);
                    } else {
                        atMobiles.push(regionManagerToMobile[region]);
                    }
                }

                if(affectedUsers >= 20) {
                    atMobiles.push(regionManagerToMobile['admin']);
                }
                if(parseTimeString(duration) <= 0.5) {
                    sendMessageTitle = "新增障碍";
                    sendMsgFlag = true;
                } else if(parseTimeString(duration) <= 4.2 && parseTimeString(duration) >= 3.6) {
                    sendMessageTitle = "临近超时障碍";
                    sendMsgFlag = true;
                    atMobiles.push(regionManagerToMobile['MrLiu']);
                    atMobiles.push(regionManagerToMobile['MrHe']);
                } else if(parseTimeString(duration) <= 6) {
                    sendMessageTitle = "未修复障碍";
                    sendMsgFlag = true;
                } else {
                    sendMessageTitle = "超6小时未修复障碍";
                    sendMsgFlag = true;
                }
                let message = `-----${sendMessageTitle}--------- \n` +
                `${gfName}\n` +
                `区县:${region}\n` +
                `${nodeInfoName[0]}\n` +
                `故障历时:${duration}\n` +
                `影响用户数量:${affectedUsers}\n` +
                `影响装维人员:${installer}\n` +
                `发送短信量:${smsCount}\n`;

                if(gforderid) {
                    if(allQueryInfo.has(gforderid)) {
                        break;
                    } else {
                        allQueryInfo.set(gforderid,message);
                    }
                }
                if(sendMsgFlag === true) {
                    sendDingTalkMessage(accessToken,message,atMobiles);
                    thisRadio.click();
                    await run();
                    thisRadio.click();
                }
            }
            resolve();
        });
    }

    // Seven Step
    function locateAndClickSendSmsButton(){
        return new Promise(function(resolve,reject){
            let iframeMain = document.getElementsByName('mainFrame');
            if(iframeMain.length === 0) {
                reject(new Error('未找到 class 为 mainFrame 的 iframe 元素'));
                return;
            }
            let iframeMainDocument = iframeMain[0].contentDocument || iframeMain[0].contentWindow.document;
            let sendButtons = iframeMainDocument.querySelectorAll("a.btnAct");
            for (let sendButton of sendButtons) {
                if (sendButton.innerText === "发送短信") {
                    sendButton.click(); 
                    resolve();
                    break;
                }
            }
        });
    }

    // Eight Step
    function chooseSendSmsContent(){
        return new Promise(function(resolve,reject){
            var iframeOpeninstallAssign = document.getElementsByName('OpeninstallAssign');
            var iframeOpenDocument = iframeOpeninstallAssign[0].contentDocument || iframeOpeninstallAssign[0].contentWindow.document;
            var radioElement = iframeOpenDocument.querySelector('input[type="radio"][name="msgId"][value="1"]');
            if (radioElement) {
                radioElement.click();
                resolve();
            } else {
                console.log("未找到匹配的<input>元素");
            }
        });
    }

    // Nine Step
    function confirmSendSms(){
        return new Promise(function(resolve,reject){
            var iframeOpeninstallAssign = document.getElementsByName('OpeninstallAssign');
            var iframeOpenDocument = iframeOpeninstallAssign[0].contentDocument || iframeOpeninstallAssign[0].contentWindow.document;
            var confirmButtons = iframeOpenDocument.querySelectorAll("a.btn.btn_sp");
            for (const confirmButton of confirmButtons) {
                if (confirmButton.innerText === "确定") {
                    confirmButton.click();
                    resolve();
                    break;
                }
            }
        });
    }

    // Ten Step
    function closeConfirmWindow(){
        return new Promise(function(resolve,reject){
            var iframeOpeninstallAssign = document.getElementsByName('OpeninstallAssign');
            var iframeOpenDocument = iframeOpeninstallAssign[0].contentDocument || iframeOpeninstallAssign[0].contentWindow.document;
            var con2Buttons = iframeOpenDocument.querySelectorAll("button.aui_state_highlight");
            for (const con2Button of con2Buttons) {
                if (con2Button.innerText === "确定") {
                    con2Button.click();
                    resolve();
                    break;
                }
            }
        });
    }
    function run(){
        return locateAndClickSendSmsButton()
                    .then(() => new Promise(resolve => setTimeout(resolve, 10000)))
                    .then(()=>chooseSendSmsContent())
                    .then(() => new Promise(resolve => setTimeout(resolve, 2000)))
                    .then(()=>confirmSendSms())
                    .then(() => new Promise(resolve => setTimeout(resolve, 6000)))
                    .then(()=>closeConfirmWindow())
                    .then(() => new Promise(resolve => setTimeout(resolve, 3000)))
                    .catch(function(error) {
                        console.log('执行7to10出错了:', error);
                    });
    }

    function runFirstToSeven(){
        return findAndClickGroupObstacleManagement()
                .then(() => new Promise(resolve => setTimeout(resolve, 2000)))
                .then(()=>findAndClickGroupObstacleQuery())
                .then(() => new Promise(resolve => setTimeout(resolve, 2000)))
                .then(()=>locateAndSetGroupObstacleType())
                .then(() => new Promise(resolve => setTimeout(resolve, 2000)))
                .then(()=>locateAndSetGroupObstacleState())
                .then(() => new Promise(resolve => setTimeout(resolve, 2000)))
                .then(()=>locateAndClickTheQueryButton())
                .then(() => new Promise(resolve => setTimeout(resolve, 8000)))
                .then(()=>getInputData())
                .then(() => new Promise(resolve => setTimeout(resolve, 4000)))
                .catch(function(error) {
                    console.log('执行1到6出错了:', error);
                });
    }
})();
